package com.ruix.app.widget;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.text.Html;
import android.text.Selection;
import android.text.Spanned;
import android.util.AttributeSet;
import android.webkit.URLUtil;
import android.widget.EditText;

import com.ruix.app.util.LogUitl;

import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hadexs on 2017/6/3.
 */

public class MyEditText extends EditText {

    public MyEditText(Context context) {
        super(context);
    }

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTextContextMenuItem(int id) {
        if (handelMenu(id)) {
            return true;
        }
        return super.onTextContextMenuItem(id);
    }

    private boolean handelMenu(int id) {
        switch (id) {
            case android.R.id.paste:
                int min = 0;
                int max = getText().length();
                return pasteself(min, max, true /* withFormatting */);
        }

        return false;
    }

    private boolean pasteself(int min, int max, boolean withFormatting) {
        ClipboardManager clipboard =
                (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = clipboard.getPrimaryClip();
        if (clip != null && clip.getItemCount() > 0) {
            CharSequence text = clip.getItemAt(0).getText();
            if (text != null) {
                if (findURL(text)) {
                    String result = String.format(" %s ", text);
                    (getText()).insert(getSelectionEnd(), result);
                    return true;
                }
            }

        }

        return false;
    }

    private boolean findURL(CharSequence contentText) {
        String regex = "[a-zA-z]+://[^\\s]*";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(contentText);
        return matcher.find();
    }
}
